import { MessageType } from '@/constants/chat';
import { useScrollToBottom } from '@/hooks/logic-hooks';
import { IAnswer } from '@/interfaces/database/chat';
import { IMessage } from '@/pages/chat/interface';
import { buildMessageUuid } from '@/utils/chat';
import { omit } from 'lodash';
import { useCallback, useEffect, useState } from 'react';
import { v4 as uuid } from 'uuid';

interface UseSharedMessagesProps {
  conversationId: string;
}

export const useSharedMessages = ({
  conversationId,
}: UseSharedMessagesProps) => {
  const [derivedMessages, setDerivedMessages] = useState<IMessage[]>([]);
  const [sessionId, setSessionId] = useState<string>('');
  const ref = useScrollToBottom(derivedMessages);

  // 生成存储键
  const getStorageKey = useCallback(
    (key: string) => {
      return `shared_chat_${key}_${conversationId}`;
    },
    [conversationId],
  );

  // 从 localStorage 加载历史消息
  const loadMessagesFromStorage = useCallback(() => {
    const messagesKey = getStorageKey('messages');
    const sessionKey = getStorageKey('sessionId');

    const storedMessages = localStorage.getItem(messagesKey);
    const storedSessionId = localStorage.getItem(sessionKey);

    if (storedMessages) {
      try {
        const messages = JSON.parse(storedMessages);
        setDerivedMessages(messages);
      } catch (error) {
        console.warn('Failed to parse stored messages:', error);
      }
    }

    if (storedSessionId) {
      setSessionId(storedSessionId);
    } else {
      // 如果没有存储的 sessionId，生成一个新的并保存
      const newSessionId = uuid();
      setSessionId(newSessionId);
      localStorage.setItem(sessionKey, newSessionId);
    }
  }, [getStorageKey]);

  // 保存消息到 localStorage
  const saveMessagesToStorage = useCallback(
    (messages: IMessage[]) => {
      const messagesKey = getStorageKey('messages');
      try {
        localStorage.setItem(messagesKey, JSON.stringify(messages));
      } catch (error) {
        console.warn('Failed to save messages to localStorage:', error);
      }
    },
    [getStorageKey],
  );

  // 保存 sessionId 到 localStorage
  const saveSessionIdToStorage = useCallback(
    (id: string) => {
      const sessionKey = getStorageKey('sessionId');
      localStorage.setItem(sessionKey, id);
    },
    [getStorageKey],
  );

  // 页面加载时从 localStorage 恢复数据
  useEffect(() => {
    if (conversationId) {
      loadMessagesFromStorage();
    }
  }, [conversationId, loadMessagesFromStorage]);

  // 监听 derivedMessages 变化，自动保存到 localStorage
  useEffect(() => {
    if (derivedMessages.length > 0) {
      saveMessagesToStorage(derivedMessages);
    }
  }, [derivedMessages, saveMessagesToStorage]);

  // 监听 sessionId 变化，自动保存到 localStorage
  useEffect(() => {
    if (sessionId) {
      saveSessionIdToStorage(sessionId);
    }
  }, [sessionId, saveSessionIdToStorage]);

  // 添加新问题
  const addNewestQuestion = useCallback((message: any, answer: string = '') => {
    setDerivedMessages((pre) => {
      const newMessages = [
        ...pre,
        {
          ...message,
          id: buildMessageUuid(message),
        },
        {
          role: MessageType.Assistant,
          content: answer,
          id: buildMessageUuid({ ...message, role: MessageType.Assistant }),
        },
      ];
      return newMessages;
    });
  }, []);

  // 添加单个问题
  const addNewestOneQuestion = useCallback((message: any) => {
    setDerivedMessages((pre) => {
      return [
        ...pre,
        {
          ...message,
          id: buildMessageUuid(message),
        },
      ];
    });
  }, []);

  // 添加流式回答
  const addNewestAnswer = useCallback((answer: IAnswer) => {
    setDerivedMessages((pre) => {
      return [
        ...(pre?.slice(0, -1) ?? []),
        {
          role: MessageType.Assistant,
          content: answer.answer,
          reference: answer.reference,
          id: buildMessageUuid({
            id: answer.id,
            role: MessageType.Assistant,
          }),
          prompt: answer.prompt,
          audio_binary: answer.audio_binary,
          session_id: (answer as any).session_id, // 保存 session_id
          ...omit(answer, 'reference'),
        },
      ];
    });
  }, []);

  // 添加单个流式回答
  const addNewestOneAnswer = useCallback((answer: IAnswer) => {
    setDerivedMessages((pre) => {
      const idx = pre.findIndex((x) => x.id === answer.id);

      if (idx !== -1) {
        return pre.map((x) => {
          if (x.id === answer.id) {
            return { ...x, ...answer, content: answer.answer };
          }
          return x;
        });
      }

      return [
        ...(pre ?? []),
        {
          role: MessageType.Assistant,
          content: answer.answer,
          reference: answer.reference,
          id: buildMessageUuid({
            id: answer.id,
            role: MessageType.Assistant,
          }),
          prompt: answer.prompt,
          audio_binary: answer.audio_binary,
          session_id: (answer as any).session_id, // 保存 session_id
          ...omit(answer, 'reference'),
        },
      ];
    });
  }, []);

  // 删除最新消息
  const removeLatestMessage = useCallback(() => {
    setDerivedMessages((pre) => {
      const nextMessages = pre?.slice(0, -2) ?? [];
      return nextMessages;
    });
  }, []);

  // 根据 ID 删除消息
  const removeMessageById = useCallback((messageId: string) => {
    setDerivedMessages((pre) => {
      const nextMessages = pre?.filter((x) => x.id !== messageId) ?? [];
      return nextMessages;
    });
  }, []);

  // 删除当前消息之后的消息
  const removeMessagesAfterCurrentMessage = useCallback((messageId: string) => {
    setDerivedMessages((pre) => {
      const index = pre.findIndex((x) => x.id === messageId);
      if (index !== -1) {
        let nextMessages = pre.slice(0, index + 2) ?? [];
        const latestMessage = nextMessages.at(-1);
        nextMessages = latestMessage
          ? [
              ...nextMessages.slice(0, -1),
              {
                ...latestMessage,
                content: '',
                reference: undefined,
                prompt: undefined,
              },
            ]
          : nextMessages;
        return nextMessages;
      }
      return pre;
    });
  }, []);

  // 更新 sessionId（当从服务器获取到新的 sessionId 时）
  const updateSessionId = useCallback((newSessionId: string) => {
    setSessionId(newSessionId);
  }, []);

  // 重置会话：清空本地存储的 sessionId 和消息
  const resetSession = useCallback(() => {
    const messagesKey = getStorageKey('messages');
    const sessionKey = getStorageKey('sessionId');

    // 清空本地存储
    localStorage.removeItem(messagesKey);
    localStorage.removeItem(sessionKey);

    // 清空状态
    setDerivedMessages([]);
    setSessionId('');

    // 刷新页面
    window.location.reload();
  }, [getStorageKey]);

  return {
    derivedMessages,
    setDerivedMessages,
    sessionId,
    ref,
    addNewestQuestion,
    addNewestAnswer,
    removeLatestMessage,
    removeMessageById,
    addNewestOneQuestion,
    addNewestOneAnswer,
    removeMessagesAfterCurrentMessage,
    updateSessionId,
    resetSession,
  };
};
